package cn.tedu.ai.service.impl;

import cn.tedu.ai.config.AiChatConfig;
import cn.tedu.ai.entity.JsonParse;
import cn.tedu.ai.entity.RoleContent;
import cn.tedu.ai.entity.Text;
import cn.tedu.ai.service.AiChatService;
import cn.tedu.ai.util.AiChatUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Service
@Slf4j
public class AiChatServiceImpl implements AiChatService {
    @Autowired
    AiChatUtil aiChatUtil;
    @SneakyThrows
    public String chat(String text) {
        log.info("进入到聊天业务逻辑");
        log.info("开始获取鉴权地址");
        String authUrl = aiChatUtil.getAuthUrl().replace("http://", "ws://").replace("https://", "wss://");// 替换http为ws
        log.info("鉴权地址拼接处理完成: {}", authUrl);
        Request request = new Request.Builder().url(authUrl).build();
        OkHttpClient client = new OkHttpClient.Builder().build(); // 创建okhttp客户端
        StringBuilder answer = new StringBuilder();
        CompletableFuture<String> messageReceived = new CompletableFuture<>();
        log.info("开始构建请求体");
        String body = aiChatUtil.buildBody(text);
        log.info("请求体构建完成: {}", body);
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() { // 监听websocket
            @Override
            public void onOpen(WebSocket webSocket, Response response) { // 连接成功
                webSocket.send(body); // 发送请求体
            }

            @SneakyThrows
            @Override
            public void onMessage(WebSocket webSocket, String text) { // 接收消息
                JsonParse myJsonParse = AiChatUtil.json.parseObject(text, JsonParse.class); // 解析json
                //myJsonParse里存放了大模型返回的消息片段
                if (myJsonParse.getHeader().getCode() != 0) {
                    log.error("发生错误，错误码为：{}，本次请求的sid为：{}", myJsonParse.getHeader().getCode(), myJsonParse.getHeader().getSid());
                    webSocket.close(1000, "");
                }
                // 由于模型的回答是流式返回的，所以用集合存储，然后拼接
                List<Text> textList = myJsonParse.getPayload().getChoices().getText();
                for (Text temp : textList) {
                    answer.append(temp.getContent());
                }
                if (AiChatUtil.canAddHistory()) {
                    RoleContent roleContent=new RoleContent();
                    roleContent.setRole("assistant");
                    roleContent.setContent(answer.toString());
                    AiChatUtil.historyList.add(roleContent);
                } else {
                    AiChatUtil.historyList.remove(0);
                    RoleContent roleContent=new RoleContent();
                    roleContent.setRole("assistant");
                    roleContent.setContent(answer.toString());
                    AiChatUtil.historyList.add(roleContent);
                }
                if (myJsonParse.getHeader().getStatus() == 2) {
                    messageReceived.complete(answer.toString()); // 将收到的消息传递给 CompletableFuture
                }
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
            }

        });
        messageReceived.get(300, TimeUnit.SECONDS);; // 阻塞等待消息返回
        webSocket.close(1000, "Closing WebSocket connection");
        return answer.toString();
    }
}
